package com.rickpan.service;

import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 下载统计服务（可选功能）
 */
@Service
public class DownloadStatsService {
    
    // 下载统计缓存
    private final ConcurrentHashMap<Long, DownloadStats> downloadStats = new ConcurrentHashMap<>();
    
    /**
     * 记录下载开始
     */
    public void recordDownloadStart(Long fileId, Long userId, String fileName, long fileSize) {
        DownloadStats stats = new DownloadStats();
        stats.fileId = fileId;
        stats.userId = userId;
        stats.fileName = fileName;
        stats.fileSize = fileSize;
        stats.startTime = LocalDateTime.now();
        stats.downloadedBytes = new AtomicLong(0);
        
        downloadStats.put(fileId, stats);
    }
    
    /**
     * 更新下载进度
     */
    public void updateDownloadProgress(Long fileId, long downloadedBytes) {
        DownloadStats stats = downloadStats.get(fileId);
        if (stats != null) {
            stats.downloadedBytes.set(downloadedBytes);
            stats.lastUpdateTime = LocalDateTime.now();
        }
    }
    
    /**
     * 记录下载完成
     */
    public void recordDownloadComplete(Long fileId) {
        DownloadStats stats = downloadStats.get(fileId);
        if (stats != null) {
            stats.completed = true;
            stats.endTime = LocalDateTime.now();
            
            // 可以保存到数据库进行持久化
            // downloadStatsRepository.save(stats);
            
            // 清理缓存
            downloadStats.remove(fileId);
        }
    }
    
    /**
     * 获取下载统计
     */
    public DownloadStats getDownloadStats(Long fileId) {
        return downloadStats.get(fileId);
    }
    
    /**
     * 下载统计数据结构
     */
    public static class DownloadStats {
        public Long fileId;
        public Long userId;
        public String fileName;
        public long fileSize;
        public AtomicLong downloadedBytes;
        public LocalDateTime startTime;
        public LocalDateTime lastUpdateTime;
        public LocalDateTime endTime;
        public boolean completed;
        
        public double getProgress() {
            if (fileSize == 0) return 0;
            return (double) downloadedBytes.get() / fileSize * 100;
        }
        
        public long getSpeed() {
            if (startTime == null || lastUpdateTime == null) return 0;
            
            long timeElapsed = java.time.Duration.between(startTime, lastUpdateTime).toMillis();
            if (timeElapsed == 0) return 0;
            
            return downloadedBytes.get() * 1000 / timeElapsed; // bytes per second
        }
    }
}
